import 'package:flutter/material.dart';

main() => runApp(MyApp());

class CounterWidget extends InheritedWidget {
  final int count;

  CounterWidget({this.count, Widget child}) : super(child: child);

  static CounterWidget of(BuildContext context) {
    //沿着element 寻找最近的CounterWidget
    return context.dependOnInheritedWidgetOfExactType();
  }

  // 是否通知 didChangeDependencies
  @override
  bool updateShouldNotify(covariant CounterWidget oldWidget) {
    return oldWidget.count != count;
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: AppBar(
          title: Text("全局state"),
          centerTitle: true,
        ),
      ),
      body: Content(),
    );
  }
}

class Content extends StatefulWidget {
  const Content({Key key}) : super(key: key);

  @override
  _ContentState createState() => _ContentState();
}

class _ContentState extends State<Content> {
  int count = 10;
  @override
  Widget build(BuildContext context) {
    return CounterWidget(
      count: count,
      child: Column(
        children: [
          ShowData01(
            key: ValueKey(2),
          ),
          ShowData02(
            key: ValueKey(1),
          ),
          ElevatedButton(
              onPressed: () {
                setState(() {
                  count++;
                });
              },
              child: Text("+1"))
        ],
      ),
    );
  }
}

class ShowData01 extends StatefulWidget {
  const ShowData01({Key key}) : super(key: key);

  @override
  _ShowData01State createState() => _ShowData01State();
}

class _ShowData01State extends State<ShowData01> {
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    print("执行了");
  }

  @override
  Widget build(BuildContext context) {
    int count = CounterWidget.of(context).count;
    return Card(
      color: Colors.red,
      child: Text(
        "当前计数 $count",
        style: TextStyle(color: Colors.white),
      ),
    );
  }
}

class ShowData02 extends StatelessWidget {
  const ShowData02({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    int count = CounterWidget.of(context).count;
    return Card(
      color: Colors.blue,
      child: Text(
        "当前计数 $count",
        style: TextStyle(color: Colors.white),
      ),
    );
  }
}
